import json
import datetime
import copy

with open('map.csv','r') as fr:
    orig = fr.read().split('\n')

allD = []
thisD = {}


import json

def main():

    with open('combine_original_10.topojson','r') as fr:
        topoAll = json.loads(fr.read())

    with open('map.csv','r') as fr:
        orig = fr.read()
    orig = orig.split('\n')[1:]

    for item in topoAll['objects']['combine_original_7']['geometries']:
        if item['properties']['admin-level'] != 'city-district':
            item['properties']['involved'] = {}
            for i in range(0, 71):
                if i <= 21:
                    dateStr = '1月' + str(i + 10) + '日'
                elif i <= 50:
                    dateStr = '2月' + str(i - 21) + '日'
                else:
                    dateStr = '3月' + str(i - 49) + '日'
                item['properties']['involved'][str(i)] = [dateStr,0,0,0,0,0,0,0]

    # print(topoAll)
    lastDate = '10'
    lastSeq = 0
    thisD = []
    dateStart = datetime.date(2020, 1, 10)
    proceedToWrite = False
    for i in range(0, len(orig)):
        # print(i, len(orig))
        line = orig[i]
        thisL = line.split(',')

        dateFull = thisL[0]
        month = dateFull[:dateFull.find('月')]
        date = dateFull[dateFull.find('月') + 1: dateFull.find('日')]
        dateNow = datetime.date(2020, int(month), int(date))
        if dateNow == dateStart:
            dateSeq = '0'
        else:
            dateSeq = str(dateNow - dateStart)[:str(dateNow - dateStart).find('d') - 1]

        if lastDate == date:
            thisD.append(line)
        else:
            topoAll = compile(topoAll, thisD, str(int(dateSeq) - 1), lastDateFull, False)
            thisD = []
            thisD.append(line)

        lastDate = copy.deepcopy(date)
        lastDateFull = copy.deepcopy(dateFull)

    topoAll = compile(topoAll, thisD, str(int(dateSeq)), dateFull, True)


def compile(topoAll, thisD, dateSeq, dateFull, proceed):
    # print('passed', thisD)
    # print(type(thisD))
    print(thisD, dateSeq, dateFull, proceed)
    dateStart = datetime.date(2020, 1, 10)
    print(dateSeq, type(dateSeq))
    for item in topoAll['objects']['combine_original_7']['geometries']:
        if item['properties']['admin-level'] == 'province':
            thisProvinceName = item['properties']['province']

            for line in thisD:
                thisL = line.split(',')

                locType = thisL[1]
                provName = thisL[2]
                cityName = thisL[3]
                if thisL[4] == '':
                    addConfirmed = 0
                else:
                    addConfirmed = int(float(thisL[4]))

                if thisL[5] == '':
                    addCured = 0
                else:
                    addCured = int(float(thisL[5]))

                if thisL[6] == '':
                    addDead = 0
                else:
                    addDead = int(float(thisL[6]))

                if thisL[7] == '':
                    minusConfirmed = 0
                else:
                    minusConfirmed = int(float(thisL[7]))

                if thisL[7] == '':
                    minusCured = 0
                else:
                    minusCured = int(float(thisL[7]))

                if thisL[7] == '':
                    minusDead = 0
                else:
                    minusDead = int(float(thisL[7]))
                if (locType == '省级') and (provName in thisProvinceName):
                    # if lastSeq in item['properties']['involved']:
                    if thisL[10] == '':
                        totalConfirmed = 0
                    else:
                        totalConfirmed = int(float(thisL[10]))

                    if thisL[11] == '':
                        totalCured = 0
                    else:
                        totalCured = int(float(thisL[11]))

                    if thisL[12] == '':
                        totalDead = 0
                    else:
                        totalDead = int(float(thisL[12]))
                    # totalConfirmed = addConfirmed + item['properties']['involved'][dateSeq][4] + minusConfirmed
                    # totalCured = addCured + item['properties']['involved'][dateSeq][5]
                    # totalDead = addDead + item['properties']['involved'][dateSeq][6]
                    # else:
                    #     totalConfirmed = addConfirmed
                    #     totalCured = addCured
                    #     totalDead = addDead

                    item['properties']['involved'][str(dateSeq)] = \
                        [dateFull, addConfirmed, addCured, addDead, totalConfirmed, totalCured, totalDead]
                    # changeAfter = False
                    # for k, v in item['properties']['involved'].items():
                    #     if k == str(dateSeq):
                    #         changeAfter = True
                    #     if changeAfter:
                    #         item['properties']['involved'][k] = \
                    #             [dateFull, addConfirmed, addCured, addDead, totalConfirmed, totalCured, totalDead]


        if item['properties']['admin-level'] == 'city':
            thisCityName = item['properties']['city']

            for line in thisD:
                thisL = line.split(',')

                locType = thisL[1]
                provName = thisL[2]
                cityName = thisL[3]
                if thisL[4] == '':
                    addConfirmed = 0
                else:
                    addConfirmed = int(float(thisL[4]))

                if thisL[5] == '':
                    addCured = 0
                else:
                    addCured = int(float(thisL[5]))

                if thisL[6] == '':
                    addDead = 0
                else:
                    addDead = int(float(thisL[6]))

                if thisL[7] == '':
                    minusConfirmed = 0
                else:
                    minusConfirmed = int(float(thisL[7]))

                if (locType == '地区级') and (cityName in thisCityName):# and (adminName in ['上海','重庆','天津','北京'] == False):
                    if thisL[10] == '':
                        totalConfirmed = 0
                    else:
                        totalConfirmed = int(float(thisL[10]))

                    if thisL[11] == '':
                        totalCured = 0
                    else:
                        totalCured = int(float(thisL[11]))

                    if thisL[12] == '':
                        totalDead = 0
                    else:
                        totalDead = int(float(thisL[12]))

                    # if lastSeq in item['properties']['involved']:
                    #     totalConfirmed = addConfirmed + item['properties']['involved'][lastSeq][4] - minusConfirmed
                    #     totalCured = addCured + item['properties']['involved'][lastSeq][5]
                    #     totalDead = addDead + item['properties']['involved'][lastSeq][6]
                    # else:
                    #     totalConfirmed = addConfirmed
                    #     totalCured = addCured
                    #     totalDead = addDead
                    # totalConfirmed = addConfirmed + item['properties']['involved'][dateSeq][4] + minusConfirmed
                    # if (cityName == '武汉'):
                    #     print(dateSeq, addConfirmed, addConfirmed + item['properties']['involved'][dateSeq][4], minusConfirmed)
                    # totalCured = addCured + item['properties']['involved'][dateSeq][5]
                    # totalDead = addDead + item['properties']['involved'][dateSeq][6]
                    item['properties']['involved'][str(dateSeq)] = \
                        [dateFull, addConfirmed, addCured, addDead, totalConfirmed, totalCured, totalDead]
                    # changeAfter = False
                    # for k, v in item['properties']['involved'].items():
                    #     if k == str(dateSeq):
                    #         changeAfter = True
                    #     if changeAfter:
                    #         item['properties']['involved'][k] = \
                    #             [dateFull, addConfirmed, addCured, addDead, totalConfirmed, totalCured, totalDead]
                    # if dateSeq == '30':
                        # print(item['properties']['province'], item['properties']['city'], item['properties']['involved'])
                    break
    # if dateSeq == '41':
    #     for item in topoAll['objects']['combine_original_7']['geometries']:
    #         if item['properties']['city'] == '毕节市' and item['properties']['admin-level'] == 'city':
    #             print(item['properties']['city'], item['properties']['involved'])
                # print(item['properties']['involved'])
        # if item['properties']['admin-level'] in ['city-district', 'dirAdmin-district']:
        #     thisProvinceName = item['properties']['province']
        #     thisDistrictName = item['properties']['district']
        #     for k, v in data.items():
        #         for k1, v1 in v['sub-province'].items():
        #             if k in thisProvinceName and k1 in thisDistrictName:
        #                 item['properties']['confirmed'] = int(v1[0])
        #                 item['properties']['cured'] = int(v1[1])
        #                 item['properties']['dead'] = int (v1[2])
        #                 break
    print(proceed)
    if proceed:
        write2File(topoAll)

    return topoAll

def write2File(topoAll):

    sep = {'histories':[]}

    for item in topoAll['objects']['combine_original_7']['geometries']:
        if item['properties']['admin-level'] != 'city-district':
            sep['histories'].append(item['properties'])

    with open('all-03-21.topojson','w') as fw:
        fw.write(json.dumps(topoAll, separators=(',', ':'), ensure_ascii=False))

    with open('histories-03-21.json','w') as fw:
        fw.write(json.dumps(sep, separators=(',', ':'), ensure_ascii=False))

if __name__ == '__main__':
    main()


